﻿using Microsoft.AspNetCore.Mvc;
using orm.sqlsugar.api.Entities;
using SqlSugar;

namespace orm.sqlsugar.api.Controllers
{
    /// <summary>
    /// 进阶操作
    /// </summary>
    public class AdvanceController(ISqlSugarClient sqlSugarClient) 
        : SqlSugarBaseController(sqlSugarClient)
    {
        /// <summary>
        /// 事务
        /// </summary>
        [HttpPost]
        public async Task<IActionResult> Transaction()
        {
            var order = new Order
            {
                Number = DateTime.Now.ToString("yyyyMMddHHmmss"),
                TotalPrice = 1,
                CreateTime = DateTime.Now
            };

            var order2 = new Order
            {
                Number = DateTime.Now.ToString("yyyyMMddHHmmss"),
                TotalPrice = 2,
                CreateTime = DateTime.Now
            };

            try
            {

                await SqlSugarClient.Ado.BeginTranAsync();

                await SqlSugarClient.Insertable(order).ExecuteCommandAsync();
                await SqlSugarClient.Insertable(order2).ExecuteCommandAsync();

                await SqlSugarClient.Ado.CommitTranAsync();
            }
            catch (Exception)
            {
                await SqlSugarClient.Ado.RollbackTranAsync();
                throw;
            }

            return Ok("Success");
        }

        /// <summary>
        /// 雪花 ID
        /// </summary>
        [HttpGet]
        public IActionResult SnowflakeId()
        {
            return Ok(SnowFlakeSingle.Instance.NextId());
        }
    }
}
